package com.california.payopenapi.socket.channel;

import com.california.payopenapi.common.ChannelManager;
import com.california.payopenapi.socket.ChannelSocketReq;
import com.california.payopenapi.utils.JsonUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * @Description:
 * @author: KeyboardMan
 * @Date: Create in 2018-12-19:19:58
 */
@Slf4j
public class PushHandler extends ChannelInboundHandlerAdapter {


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof TextWebSocketFrame) {
            TextWebSocketFrame socketFrame = (TextWebSocketFrame) msg;
            log.info("传输的报文 {}",socketFrame.text());
            ChannelSocketReq channelSocketReq = JsonUtil.string2Obj(socketFrame.text(), ChannelSocketReq.class);
            String key = channelSocketReq.getKey();
            if (StringUtils.isEmpty(key)) {
                ctx.channel().writeAndFlush(new TextWebSocketFrame("错误的数据格式,通道关闭"));
                ReferenceCountUtil.release(msg);
            } else {
                log.info("报文校验成功 报文 ： {}",channelSocketReq);
                ChannelManager.put(key,ctx.channel());
                ReferenceCountUtil.release(msg);
            }
        } else {
            ctx.channel().writeAndFlush(new TextWebSocketFrame("错误的数据格式,通道将被关闭..."));
            ctx.channel().close();
            ReferenceCountUtil.release(msg);
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        String channelId = ctx.channel().id().asLongText();
        log.info("设备掉线 channelId {} ",channelId);
        ChannelManager.remove(channelId);
    }
}